<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>选择试卷</title>
    <jsp:include page="/layout/_imports.jsp"></jsp:include>
    <style>
        .selection {
            margin-right: 10px;
        }
        .exam_title {
            display: flex;
            position: fixed;
            width: 90%;
            background: #fff;
            top: 95px;
            padding-top: 20px;
        }
        .exam_form {
            margin-top: 120px;
        }
    </style>
</head>
<body>
<jsp:include page="/layout/_nav.jsp"></jsp:include>

<div class="container">
    <c:if test="${score==null}">
        <div id="paper_nav" class="row">
            <div class="exam_title">
                <h2 hidden class="begin_time"><fmt:formatDate value="${paper.begin}" pattern="yyyy-MM-dd HH:mm:ss"/></h2>
                <h2 class="col col-md-4">倒计时:<span class="countdown"></span></h2>
                <h2 class="col col-md-4">${paper.title}</h2>
                <div class="col col-md-4">
                    <h5>开始时间：<fmt:formatDate value="${paper.begin}" pattern="yyyy-MM-dd HH:mm:ss"/></h5>
                    <h4>时限：<span class="limitaion">${paper.limitation}</span>分钟</h4>
                    <button type="button" class="btn btn-primary end_exam">提交</button>
                    <button type="button" class="btn btn-danger quit_exam">退出</button>
                </div>
            </div>
            <form action="/exam" method="post" class="exam_form">
                <input type="hidden" name="paperId" value="${paper.id}">
                <c:forEach items="${itemes}" varStatus="item" var="i">
                    <div class="question" style="text-align: left">
                        <h4>${item.index+1}. ${i.title}</h4>
                        <input type="hidden" value="${i.id}" class="item_id" name="itemId">
                        <input type="hidden" value="${i.content}" class="to_parsed">
                        <input type="hidden" value="${i.typeId}" class="type">
                        <div class="choices">

                        </div>
                    </div>
                </c:forEach>
            </form>
        </div>
    </c:if>
    <c:if test="${score!=null}">
        <h2>您已考试完毕!</h2>
        <h2 style="color: red">您的分数是:${score}</h2>
    </c:if>

    <c:if test="${not empty errMsg}">
        <div class="alert alert-danger">${errMsg}</div>
    </c:if>
</div>

<script>
    window.onload = function () {
        var result = {};
        var begin_paper_time = $(".begin_time").text();
        var limitation = $(".limitaion").text();
        var begin_date_time = stringToDate(begin_paper_time);
        var end = new Date(begin_date_time);
        end = new Date(end.setMinutes(end.getMinutes() + Number(limitation)));
        var end_time = format(end, "yyyy-MM-dd hh:mm:ss");//结束时间


        //获取题目id
        var itemIds = document.getElementsByClassName("item_id");
        //获取问题
        var questions = document.getElementsByClassName("question");
        //获取答案选项
        var contents = document.getElementsByClassName("to_parsed");
        //获取选项地址
        var choices = document.getElementsByClassName("choices");
        //获取题目类型
        var types = document.getElementsByClassName("type");

        for (let i = 0; i < questions.length; i++) {
            var name = $(itemIds[i]).val()
            var answer = parseChoices($(contents[i]).val(), name, $(types[i]).val());
            $(choices[i]).html(answer);
        }



        function countTime(end) {
            var begin = new Date();
            var lefttime = end.getTime() - begin.getTime();  //距离结束时间的毫秒数
            var leftd = Math.floor(lefttime/(1000*60*60*24));  //计算天数
            var lefth = Math.floor(lefttime/(1000*60*60)%24);  //计算小时数
            var leftm = Math.floor(lefttime/(1000*60)%60);  //计算分钟数
            var lefts = Math.floor(lefttime/1000%60);  //计算秒数
            leftd = leftd<10?"0"+leftd:leftd;
            lefth = lefth<10?"0"+lefth:lefth;
            leftm = leftm<10?"0"+leftm:leftm;
            lefts = lefts<10?"0"+lefts:lefts;
            var count =  leftd + "天" + lefth+ ":" + leftm + ":" + lefts;  //返回倒计时的字符串
            $(".countdown").text(count);
        }

        setInterval(()=>countTime(end),1000);

        function stringToDate(strDate) {
            var tempStrs = strDate.split(" ");

            var dateStrs = tempStrs[0].split("-");
            var year = parseInt(dateStrs[0], 10);
            var month = parseInt(dateStrs[1], 10) - 1;
            var day = parseInt(dateStrs[2], 10);

            var timeStrs = tempStrs[1].split(":");
            var hour = parseInt(timeStrs [0], 10);
            var minute = parseInt(timeStrs[1], 10);
            var second = parseInt(timeStrs[2], 10);

            var date = new Date(year, month, day, hour, minute, second);
            return date;
        }

        function parseChoices(content, name, type) {
            var answers = content.split(" ")
            var choice_str = "";
            if (type === "single") {
                for(var i = 0; i < answers.length; i++) {
                    var idName = name + i;
                    var select = answers[i].split(".")
                    var str = '<input type="radio" class="selection" name="'+name+'" id="'+idName+'" value="'+select[0]+'"><label for="'+idName+'" >'+ answers[i] +'</label><br>'
                    choice_str += str;
                }
            } else if (type === "multiple") {
                for(var i = 0; i < answers.length; i++) {
                    var idName = name + i;
                    var select = answers[i].split(".")
                    var str = '<input type="checkbox" class="selection" name="'+name+'" id="'+idName+'" value="'+select[0]+'"><label for="'+idName+'" >'+ answers[i] +'</label><br>'
                    choice_str += str;
                }
            }
            return choice_str;
        }


        $(".end_exam").on('click', function () {
            for (let i = 0; i < itemIds.length; i++) {
                var id = $(itemIds[i]).val()
                var type = $(types[i]).val()
                var select_answer = document.getElementsByName(id);
                var selected = []
                if (type === "single") {
                    for (let i = 0; i < select_answer.length; i++) {
                        if (select_answer[i].checked) {
                            selected.push($(select_answer[i]).val());
                            break;
                        }
                    }
                } else if (type === "multiple") {
                    for (let i = 0; i < select_answer.length; i++) {
                        if (select_answer[i].checked) {
                            selected.push($(select_answer[i]).val());
                        }
                    }
                }
                result[id] = selected
            }
            console.log(result)
            let all_down = true;
            for(var i = 0; i < itemIds.length; i++) {
                if (result[$(itemIds[i]).val()].length === 0) {
                    all_down = false;
                }
            }
            if (all_down) {
                var checked = confirm("Are you Sure")
                if (checked === true) {
                    $(".exam_form").submit()
                }
            } else {
                alert("请完成所有题目！")
            }
        })




    }
</script>
</body>
</html>
